﻿using System;
using UnityEngine;

namespace GameDesigner
{
    [Serializable]
    public class StateLayer : IStateLayer
    {
        public string name;
        public StateMachine stateMachine;
        public IStateMachine StateMachine { get => stateMachine; set => stateMachine = (StateMachine)value; }
        [SerializeField] private AvatarMask avatarMask;
        public AvatarMask AvatarMask { get => avatarMask; set => avatarMask = value; }
        private static AvatarMask defaultMask;
        public AvatarMask DefaultMask => defaultMask = defaultMask != null ? defaultMask : CreateAvatarMask(true); //当不reload程序集时要判断是否==null实际上是"null"
        private static AvatarMask disableMask;
        public AvatarMask DisableMask => disableMask = disableMask != null ? disableMask : CreateAvatarMask(false);
        [SerializeField] private float weight;
        public float Weight { get => weight; set => SetLayerWeight(value, false); }
        public bool IKPass { get; set; }
        public int LayerIndex { get; set; }

        public void Execute(StateMachineUpdateMode update)
        {
            stateMachine.Execute(update);
        }

        public void SetLayerMask(AvatarMask avatarMask)
        {
            this.avatarMask = avatarMask;
            stateMachine.Handler?.ApplyLayerMask();
        }

        public void SetLayerWeight(float weight, bool isCrossFade = true)
        {
            this.weight = weight;
            stateMachine.Handler?.ApplyLayerWeight(isCrossFade);
        }

        public float GetLayerWeight()
        {
            return weight;
        }

        private AvatarMask CreateAvatarMask(bool value)
        {
            var avatarMask = new AvatarMask();
            for (int i = 0; i < (int)AvatarMaskBodyPart.LastBodyPart; i++)
                avatarMask.SetHumanoidBodyPartActive((AvatarMaskBodyPart)i, value);
            return avatarMask;
        }
    }
}